package P150;

import java.util.HashSet;
import java.util.Set;

public class P50 {

    public static String simplifyPath(String path) {
        // 切割
        String[] split = path.split("/");
        // 忽略集合
        Set<String> set = new HashSet<>();
        set.add(".");
        set.add("");
        set.add(" ");
        // 遍历处理
        for (int i = 0; i < split.length; i++) {
            if (split[i].equals("..")) {
                split[i] = "";
                for (int j = i - 1; j > 0; --j) {
                    if (!set.contains(split[j])) {
                        split[j] = "";
                        break;
                    }
                }
            }
        }
        //合并
        StringBuilder res = new StringBuilder();
        for (String s : split) {
            if (!set.contains(s)) {
                res.append("/").append(s);
            }
        }
        return res.length() == 0 ? "/" : res.toString();
    }


    public static void main(String[] args) {
        String path1 = "/home/";
        String path2 = "/../";
        String path3 = "/home//foo/";
        String path4 = "/a/./b/../../c/";
        String path5 = "/home/user/Documents/../Pictures";
        System.out.println(simplifyPath(path1));
        System.out.println(simplifyPath(path2));
        System.out.println(simplifyPath(path3));
        System.out.println(simplifyPath(path4));
        System.out.println(simplifyPath(path5));
    }

}
